/*
观察者模式定义了一种一对多的依赖关系，让多个观察者对象同时监听某一个目标对象，当这个目标对象的状态发生变化时，会通知所有观察者对象，使它们能够自动更新

主题对象(Subject) 该角色又称为被观察者,可以增加和删除观察者对象,它将有关状态存入具体观察者对象，在具体主题的内部状态改变时，给所有登记过(关联了观察关系)的观察者发出通知
观察者(Observer)角色：定义一个接收通知的接口(update),在得到主题的通知时更新自己

*/
abstract class Student {
  constructor(public teacher: Teacher) {

  }

  public abstract update(): void;
}

class Xueba extends Student {
  public update(): void {
    if (this.teacher.getState() === '提问') {
      console.log(this.teacher.getState(),'抬头举手')
    }
  }
}

class XueZha extends Student {
  public update(): void {
    if (this.teacher.getState() === '提问') {
      console.log(this.teacher.getState(),'低头看脚')
    }
  }
}

class Teacher {
  private students: Student[] = [];
  private state: string = '讲课';

  public askQuestion() {
    this.state = '提问'
    this.notifyAllStudents()
  }

  getState() {
    return this.state
  }

  attach(student: Student) {
    this.students.push(student)
  }

  notifyAllStudents() {
    this.students.forEach(student => student.update())
  }
}

const teacher = new Teacher()
teacher.attach(new Xueba(teacher))
teacher.attach(new XueZha(teacher))
teacher.askQuestion()
